package controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Utente;
import dbms.Postgres;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Postgres p = Postgres.getInstance();
		String pw = request.getParameter("pw");
		String user = request.getParameter("user");
		ResultSet rs = p.loginQuery(pw, user);
		try {
			if (rs.next()) {
				Utente ut = new Utente();
				ServletContext sc = getServletContext();
				RequestDispatcher rd = sc.getRequestDispatcher("/QueryServlet");
				rd.forward(request, response);
				ut.setId(Integer.parseInt(rs.getString("id")));
				ut.setIda(Integer.parseInt(rs.getString("ida")));
				ut.setPassword(rs.getString("password"));
				ut.setRuolo(rs.getString("ruolo"));
				ut.setUsername(rs.getString("username"));
				request.getSession().setAttribute("utente", ut);

			} else {
				response.sendRedirect("errore.html");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
